<?php

namespace App\Models;

use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Notifications\ResetPassword as ResetPasswordNotification;

/**
 * 系统用户数据模型
 * @package App\Models
 */
class SysUser extends Authenticatable
{
    use HasApiTokens,Notifiable, SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * 重置密码重构
     * @param string $token
     */
    public function sendPasswordResetNotification($token)
    {
        $this->notify(new ResetPasswordNotification($token));
    }

    /**
     * 获取用户角色列表
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function roles()
    {
        return $this->belongsToMany('App\Models\SysRole','sys_role_users','user_id','role_id')->withTimestamps();
    }

    /**
     * 判断用户是否具有某个角色
     * @param $role
     * @return bool
     */
    public function hasRole($role)
    {
        if (is_string($role)){
            return $this->roles->contains('name', $role);
        }
        //判断拥有该权限的角色和当前用户的角色是否有重合存在交集。双感叹号相当于强制转换为布尔类型
        return !! $role->intersect($this->roles)->count();
    }

    /**
     * 判断用户是否具有某权限
     * @param $permission
     * @return bool
     */
    public function hasPermission($permission)
    {
        if ($permission->is_public == 1){//公共权限直接返回true
            return true;
        }else{
            //判断是否是超级管理员
            if ($this->hasRole('supper-admin')){
                return true;
            }else{
                return $this->hasRole($permission->roles);
            }
        }
    }

    /**
     * 给用户分配角色
     * @param $role
     * @return \Illuminate\Database\Eloquent\Model
     */
    public function assignRole($role)
    {
        return $this->roles()->save(
            SysRole::whereName($role)->firstOrFail()
        );
    }
}
